﻿
now.ready(function () {

    $("#msg").removeAttr("disabled");
    now.runTimer();
    //alert("now.ready() fires up");
    $('#chat form').submit();
    now.getStockList();
    //$("#scroller").simplyScroll();
    now.sGetName();

});

$(document).ready(function () {
    if ($("#msg").attr("disabled") == undefined) {
        $("#msg").attr("disabled", "disabled");
    }


    function Message(data) {
        this.message = ko.observable(data.message)
    }

    function Game() {
        // Data
        var self = this;
        self.message = ko.observableArray([]);
        self.newMessage = ko.observable();
        self.stockList = ko.observableArray([]);
        self.stock = ko.observable();
        self.userStockList = ko.observableArray([]);
        self.user = ko.observable();
        self.unitPrice = ko.observable(1);

        self.userBudget = 1000;
        self.stockQty = ko.observable();
        self.buyStockQty = ko.observable(0);
        self.sellQty = ko.observable(0)

        self.errorMessage = ko.observable("");

        // Operations
        // to calculate userCredit - which happens in indtex.html
        var totalsum = 0;
        self.userCredit = ko.computed(function () {
            _userCredit = parseInt(self.buyStockQty()) * parseInt(self.unitPrice());
            totalsum += _userCredit;
            return totalsum;
        }, this);

        //chat communcation with server and users
        self.addMessage = function () {
            now.distributeMessage(this.newMessage());

            now.receiveMessage = function (name, msg) {
                this.newMessage = (name + ": " + msg);

                self.message.push(new Message({ message: this.newMessage }));
                self.newMessage("");
                $("#chatWindow").prop("scrollTop", $('#chatWindow').height());
            }
        };

        now.cGetName = function (userName) {
            self.user(userName);
        }

        //gets stocklist from server.
        now.receiveStocks = function (stocklist) {
            self.stockList.removeAll();

            for (var i = 0; i < stocklist.length; i++) {
                self.stockList.push(stocklist[i]);
            }
        }
        // handles buying stocks
        self.buyStock = function (stock) {
            var moneyToSpend = (stock.unitPrice * parseInt(stock.stockQty));
            var moneyCanSpend = self.userCredit() + self.userBudget;
            if (stock.stockQty != 0 && moneyToSpend <= moneyCanSpend) {
                var stocksum = 0;
                var found = false;

                for (var i = 0; i < self.userStockList().length; i++) {

                    if (stock.EPIC == self.userStockList()[i].EPIC) {
                        stocksum = self.userStockList()[i].stockQty + parseInt(stock.stockQty);
                        self.userStockList.remove(self.userStockList()[i]);
                        self.userStockList.push({ EPIC: stock.EPIC, stockQty: parseInt(stocksum), sellQty: 0 });
                        found = true;
                        self.unitPrice(stock.unitPrice);
                        self.buyStockQty(-stock.stockQty);
                        self.buyStockQty(0);
                        self.unitPrice(1);


                    }
                }

                if (found == false || self.userStockList().length == 0) {
                    self.userStockList.push({ EPIC: stock.EPIC, stockQty: parseInt(stock.stockQty), sellQty: 0 });
                    self.unitPrice(stock.unitPrice);
                    self.buyStockQty(-stock.stockQty);
                    self.buyStockQty(0);
                    self.unitPrice(1);



                }
                now.customerInfluence(stock.EPIC, stock.stockQty, "buy");
            }
            else
                alert(" Not enough money! ");

        }

        self.sellStock = function (stock) {
            var found = false;
            var stockCounter = 0;
            var newUnitprice = 0;
            if (self.userStockList().length != 0 && stock.sellQty != 0) {
                for (var i = 0; i < self.userStockList().length; i++) {
                    //find stock to sell in user array
                    if (stock.EPIC == self.userStockList()[i].EPIC) {
                        if (stock.sellQty <= self.userStockList()[i].stockQty) {
                            // sellQty is a variable created when a stock was bought.
                            stockCounter = parseInt(self.userStockList()[i].stockQty) - parseInt(self.userStockList()[i].sellQty)
                            // get current price value of stock
                            for (var f = 0; f < self.stockList().length; f++) {

                                if (self.userStockList()[i].EPIC == self.stockList()[f].EPIC) {
                                    found = true;
                                    newUnitprice = (self.stockList()[f].unitPrice);
                                }
                            }
                            // to update userCredit and update userStockList
                            if (found == true) {
                                self.unitPrice(newUnitprice) //userCredit()
                                self.buyStockQty(stockCounter); //userCredit()
                                self.userStockList.remove(self.userStockList()[i]); //remove from userStockList-Array
                                self.userStockList.push({ EPIC: stock.EPIC, stockQty: parseInt(stockCounter), sellQty: 0 }); // insert updated values - stock.stockQty has selling number
                                self.buyStockQty(0); // reinitialize for calculation in userCredit
                                self.unitPrice(1); // reinitialize for calculation in userCredit

                            }
                        }
                        else {
                            stockCounter = self.userStockList()[i].stockQty;
                            for (var f = 0; f < self.stockList().length; f++) {

                                if (self.userStockList()[i].EPIC == self.stockList()[f].EPIC) {
                                    found = true;
                                    newUnitprice = (self.stockList()[f].unitPrice);
                                }
                            }
                            // to update userCredit and update userStockList
                            if (found == true) {
                                self.unitPrice(newUnitprice) //userCredit()
                                self.buyStockQty(stockCounter); //userCredit()
                                self.userStockList.remove(self.userStockList()[i]); //remove from userStockList-Array
                                //                            self.userStockList.push({ EPIC: stock.EPIC, stockQty: 0, sellQty: 0 }); // insert updated values - stock.stockQty has selling number
                                self.buyStockQty(0); // reinitialize for calculation in userCredit
                                self.unitPrice(1); // reinitialize for calculation in userCredit
                            }

                        }
                    }

                }
            }
            now.customerInfluence(stock.EPIC, stock.sellQty, "sell");
        }

        // doubleganger
        self.sellAllStock = function (stock) {

            if (self.userStockList().length != 0) {
                for (var i = 0; i < self.userStockList().length; i++) {
                    //find stock to sell in user array
                    if (stock.EPIC == self.userStockList()[i].EPIC) {
                        if (stock.sellQty <= self.userStockList()[i].stockQty) {
                            // sellQty is a variable created when a stock was bought.
                            stockCounter = parseInt(self.userStockList()[i].stockQty)
                            // get current price value of stock
                            for (var f = 0; f < self.stockList().length; f++) {
                                if (self.userStockList()[i].EPIC == self.stockList()[f].EPIC) {
                                    found = true;
                                    newUnitprice = (self.stockList()[f].unitPrice);
                                }
                            }
                            // to update userCredit and update userStockList
                            if (found == true) {
                                self.unitPrice(newUnitprice) //userCredit()
                                self.buyStockQty(stockCounter); //userCredit()
                                self.userStockList.remove(self.userStockList()[i]); //remove from userStockList-Array
                                //                                self.userStockList.push({ EPIC: stock.EPIC, stockQty: 0, sellQty: 0 }); // sell all stockQty cero
                                self.buyStockQty(0); // reinitialize for calculation in userCredit
                            }
                        }
                    }
                }
            }
            now.customerInfluence(stock.EPIC, stock.sellQty, "sell")
        }


        now.reportUserStatus = function (user, status) {
            self.message.push(new Message({ message: "SERVER: " + user + " has " + status + " the chat" }));
            self.newMessage("");
        }

        now.findWinner = function () {
            //alert("bleh");
            now.sendScoreToServer((self.userCredit() + self.userBudget));
        }

        now.announceWinner = function (name) {
            alert("...og sigurvegarinn er......" + name);
        }

        now.resetUserCredit = function () {
            self.userCredit(0);
        }

        now.clearUserArray = function () {
            self.userStockList.removeAll();
        //HAFA ALLT HÉR INNI

    }

    ko.applyBindings(new Game());


    //timer related
    now.displayTime = function (jsonTime) {
        var obj = eval("(" + jsonTime + ")");
        var min = "";
        var sec = "";

        if (obj.time[0].min >= 0 && obj.time[0].min < 10) {
            min = "0" + obj.time[0].min;
        } else min = obj.time[0].min;

        if (obj.time[0].sec >= 0 && obj.time[0].sec < 10) {
            sec = "0" + obj.time[0].sec;
        } else sec = obj.time[0].sec;

        $("#timer p").text(min + ":" + sec);
    }
    //end timer related


    //other stuff

    var chatHeight = $(window).height() - 75;
    $('#chatWindow').css("height", chatHeight);

    var mainHeight = $(window).height() - 164;
    $('#main').css("height", mainHeight);

    $(window).resize(function () {
        var chatHeight = $(window).height() - 75;
        $('#chatWindow').css("height", chatHeight);

        var mainHeight = $(window).height() - 164;
        $('#main').css("height", mainHeight);
    });




    //end other stuff

});
